import { request } from '../../request/index.js';
var startX, endX;
var moveFlag = true;// 判断执行滑动事件
Page({
  data: {
    module: [true, false],
    nowPage: [0, 0],
    module_HoverBox: false,//悬浮提示框状态
    myFavorites: [],
    myMerch: [],
  },
  onLoad: function (options) {
    let userId = wx.getStorageSync('userId')
    let url1 = `/commodityFav/get/${userId}/1` //收藏
    let url2 = `/commodity/getU/${userId}/0/1/1` //个人商品
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    this.Search(url1, 0, 1)
    this.Search(url2, 1, 1)
    wx.hideLoading()
  }, onReady: function (options) {
  }, onPageScroll: function (e) {
    this.tanchu(1)
  }, onPullDownRefresh() {//下拉
    this.onLoad()
    wx.stopPullDownRefresh()//得到结果后关掉刷新动画
  }, onReachBottom() {//上拉
    let url
    let userId = wx.getStorageSync('userId')
    if (this.data.module[0]) {
      url = `/commodityFav/get/${userId}/${this.data.nowPage[0] + 1}` //收藏
      this.Search(url, 0, this.data.nowPage[0] + 1)
    } else {
      url = `/commodity/getU/${userId}/0/1/${this.data.nowPage[1] + 1}` //个人商品
      this.Search(url, 1, this.data.nowPage[1] + 1)
    }
  }, async Search(url, m, curPage) {//查询接口 m表示哪个页面的 curPage表示请求第几个页面
    let _this = this
    let nowArray
    const { data } = await request({
      url: url
    })
    console.log(data)
    if (data.state === 1) {
      var _data = data.data.commodities
      let p = 1;//重置当前页面需要的页数，有数据则是一页重置，无数据则是零页重置
      if (!_data||_data.length==0) {
        _data=[]
        --curPage;
        p = 0;
      } else {
        for (var i = 0; i < _data.length; i++) {
          var img = _data[i].imgs
          var imgs = []
          if (img) {
            imgs = img.split("|")//分割图片数组
            imgs = imgs.slice(0, imgs.length - 1)//去除末尾空值
          }
          _data[i].imgs = imgs
        }
      }
      let _nowPage = this.data.nowPage
      _nowPage[m] = curPage
      if (curPage == p) {
        if (m == 0) {
          _this.setData({
            myFavorites: _data,
            nowPage: _nowPage
          })
        } else if (m == 1) {
          _this.setData({
            myMerch: _data,
            nowPage: _nowPage
          })
        }
      } else {
        if (m == 0) {
          nowArray = [...this.data.myFavorites,..._data]
          _this.setData({
            myFavorites: nowArray,
            nowPage: _nowPage
          })
        } else if (m == 1) { 
          nowArray = [...this.data.myMerch,..._data ]
          _this.setData({
            myMerch: nowArray,
            nowPage: _nowPage
          })
        }
      }
    } else {
      wx.showToast({
        title: '访问太频繁',
        icon: 'error',
        duration: 2000,
        mask: false,
      })
      if (curPage == 0) {
        if (m == 0) {
          _this.setData({
            myFavorites: [],
          })
        } else if (m == 1) {
          _this.setData({
            myMerch: [],
          })
        }
      }
    }
    this.judgmentH()
  },
  touchStart: function (e) {
    startX = e.touches[0].pageX; // 获取触摸时的原点
    moveFlag = true;
  }, touchMove: function (e) {
    endX = e.touches[0].pageX; // 获取触摸时的原点
    if (moveFlag) {
      if (endX - startX > 50) {
        let toRight = { currentTarget: { dataset: { module: 0 } } }
        this.shiftModule(toRight);
        moveFlag = false;
      }
      if (startX - endX > 50) {
        let toLeft = { currentTarget: { dataset: { module: 1 } } }
        this.shiftModule(toLeft);
        moveFlag = false;
      }
    }
  }, touchEnd: function (e) {
    moveFlag = true; // 回复滑动事件
  },
  async judgmentH() {//防止两个页面贯穿
    const _this = this
    function judgmenth(className) {
      return new Promise((resolve, reject) => {
        let query = wx.createSelectorQuery();
        query.select(className).boundingClientRect(res => {
          resolve(res.height)
        }).exec()
      })
    }
    let CH = await judgmenth('.commodity_collection')
    let SH = await judgmenth('.commodity_Shelves')
    let H
    if (this.data.module[0])
      H = CH
    else
      H = SH
    _this.setData({
      commodity_collection_H: CH,
      commodity_Shelve_H: SH,
      commodity_data_H: H
    })
  },
  tanchu(i) {//弹出功能按钮
    let animation = wx.createAnimation({
      duration: 1000,
      timingFunction: 'linear',
      delay: 0,
    });
    let mH = this.data.module_HoverBox
    if (i == 1) {
      if (!mH) {
        return
      }
    }
    if (!mH) {
      animation.translateY('-450rpx')
      animation.opacity(1)
      animation.rotate(360).step();
    } else {
      animation.translateY('0')
      animation.opacity(0)
      animation.rotate(-360).step();
    }
    mH = !mH
    this.setData({
      module_HoverBox: mH,
      animation_HoverBox: animation
    })
  },
  shiftModule(e) {//翻页
    var x = e.currentTarget.dataset.module
    let animationA = wx.createAnimation({
      duration: 300,
      timingFunction: 'linear',
      delay: 0,
    });
    let animationB = wx.createAnimation({
      duration: 100,
      timingFunction: 'linear',
      delay: 0,
    });
    let H
    if (x == 0) {
      animationA.translateX('0')
      animationA.opacity(1).step();
      animationB.opacity(0).step();
      var arr = [true, false]
      H = this.data.commodity_collection_H
    } else {
      animationA.translateX('-750rpx')
      animationA.opacity(0).step();
      animationB.opacity(1).step();
      var arr = [false, true]
      H = this.data.commodity_Shelve_H
    }
    this.setData({
      animationA: animationA,
      animationB: animationB,
      module: arr,
      commodity_data_H: H
    })
  },
  toDetailPage(e) {//前往商品详细页面
    let position = e.mark.position
    let id = e.mark.id
    let index = e.mark.index
    let nextData = {}
    let list = []
    if (position == 0) {
      list = this.data.myFavorites
    } else {
      list = this.data.myMerch
    }
    if (list[index].id == id) {
      nextData = list[index]
      let data = JSON.stringify(nextData)
      wx.navigateTo({
        url: `/pages/FMDetailPage/FMDetailPage?nextData=${data}`
      })
    } else {
      wx.showToast({
        title: "系统繁忙", // 提示的内容
        icon: "loading", // 图标，默认success
        duration: 3000, // 提示的延迟时间，默认1500
        mask: true, // 是否显示透明蒙层，防止触摸穿透
        success: function () {
          console.log("信息不匹配");
        },
        fail: function () {
          console.log("接口wx.showToast调用失败");
        },
      })
    }
  },
  toDelete(e) {//删除
    let _this = this
    let id = e.mark.id
    let index = e.mark.index
    let position = e.mark.position
    let list = []
    function showModal0() {//取消收藏
      return new Promise((resolve, reject) => {
        wx.showModal({
          title: '取消收藏',
          content: '是否取消该收藏',
          confirmColor: "rgb(255,80,0)",
          success: async function (res) {
            if (res.confirm) {//这里是点击了确定以后    
              list = [..._this.data.myFavorites]
              if (list[index].id == id) {//二次确定
                let userId = wx.getStorageSync('userId')
                const { data } = await request({
                  url: `/commodityFavorites/delete/${id}/${userId}`
                })
                if (data.state == 1) {
                  list.splice(index, 1)
                  _this.setData({
                    myFavorites: list
                  })
                  resolve()
                } else {
                  reject()
                }
              }
            } else {//这里是点击了取消以后
            }
          },
          fail: function () {
            reject()
          }
        })
      })
    }
    function showModal1() {//下架
      return new Promise((resolve, reject) => {
        wx.showModal({
          title: '下架',
          content: '是否下架该商品',
          confirmColor: "rgb(255,80,0)",
          success: async function (res) {
            if (res.confirm) {//这里是点击了确定以后  
              list = [..._this.data.myMerch]
              if (list[index].id == id) {
                const { data } = await request({
                  url: `/commodity/delete/${id}`
                })
                if (data.state == 1) {
                  list.splice(index, 1)
                  _this.setData({
                    myMerch: list
                  })
                  resolve()
                } else {
                  reject()
                }
              }
            } else {//这里是点击了取消以后
            }
          },
          fail: function () {
            reject()
          }
        })
      })
    }
    let showModal = showModal1
    if (position == 0) {
      showModal = showModal0
    }
    showModal().then(res => {
      wx.showToast({
        title: "成功", // 提示的内容
        icon: "success", // 图标，默认success
        duration: 500, // 提示的延迟时间，默认1500
        mask: true, // 是否显示透明蒙层，防止触摸穿透
        success: function () {
          console.log("成功");
        },
        fail: function () {
          console.log("接口wx.showToast调用失败1");
        },
      })
    }, function () {
      wx.showToast({
        title: "系统繁忙", // 提示的内容
        icon: "loading", // 图标，默认success
        duration: 3000, // 提示的延迟时间，默认1500
        mask: true, // 是否显示透明蒙层，防止触摸穿透
        success: function () {
          console.log("showModal 失败");
        },
        fail: function () {
          console.log("接口wx.showToast调用失败2");
        },
      })
    })
  }
})